const { Service } = require('egg');

const moment = require('moment');
const { v4: uuidV4 } = require('uuid');
const table_name = 'permission';


class HomeService extends Service {
  // 路由初始化
  async init() {
    const knex = this.app.knex;
    try {
      const list = [];
      const { stack } = this.app.router;
      const time = moment();

      const interface_list = await knex(table_name).select('uuid', 'url', 'key').where({ model: 'ORDER', is_delete: 0 });

      for (const s of stack) {
        const method = s.methods[s.methods.length - 1];
        const key = `${method}${s.path.replace(/\//g, ':')}`;
        const interfaces = interface_list.find(f => {
          return f.key === key;
        });

        if (!interfaces) {
          const obj = {
            uuid: uuidV4().replace(/-/g, ''),
            model: 'ORDER',
            name: s.name,
            key: `${method}${s.path.replace(/\//g, ':')}`,
            url: s.path,
            method,
            type: 1,
            status: 1,
            parent_id: '-1',
            create_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
            update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
            create_by: '-1',
            update_by: '-1',
            is_delete: 0,
          };

          list.push(obj);
        }
      }


      if (list.length !== 0) {
        await knex(table_name).insert(list);
      }

      return 'success';
    } catch (error) {
      console.log(error);
      throw new Error('service错误');
    }
  }
}

module.exports = HomeService;
